package com.wangbo.rabbit;

import com.rabbitmq.client.Channel;
import com.wangbo.rabbit.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyMessageHandler implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        // 邮递标签，消息在 Broker 中的唯一标识
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 消息来源队列名
        String queueName = message.getMessageProperties().getConsumerQueue();

        try {
            // 获取消息
            String msg = new String(message.getBody()).trim();
            RabbitMessage rabbitMessage = JacksonUtil.toBean(msg, RabbitMessage.class);
            log.info("收到消息：messageId={}, payload={}", rabbitMessage.getMessageId(), rabbitMessage.getPayload());

            // 确认，false 表示只确认当前消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            // 拒绝，true 表示消息放回队列
            channel.basicReject(deliveryTag, true);
        }

    }
}
